package kamkor.ann.namerecog.network.trainer

import java.io.File
import java.io.PrintStream
import scala.io.Source
import scala.collection.mutable.HashMap
import kamkor.ann.namerecog.network.parser._
import kamkor.ann.namerecog.network.converter._

/**
 * 
 * @author kamkor
 *
 */
object Trainer {	
	def main(args: Array[String]) {
		main(args, System.out)
	}
	
	def main(args: Array[String], console: PrintStream) {	
		// todo: catch exception and print error
		val argsMap = TrainerArgsParser.parseArgs(args)
		
		// parse conversion map and setup converters
		val mappingFilePath = argsMap(TrainerArgsParser.mapKey)
		val mappingParser = new ConversionMapXmlParser(new File(mappingFilePath))		
		val inputConverter = new InputConverter(mappingParser.inputConversionMap)		
		
		// parse training data
		val inputFiles = argsMap(TrainerArgsParser.trainingDataKey).split(",")
		// polish group, russian group, german group etc
		val surnamesGroups = 
			for (file <- inputFiles) yield Source.fromFile(file, "UTF-8").mkString		
		val parsedSurnames =
			for (surnames <- surnamesGroups) yield SurnamesParser.parse(surnames, _.toLowerCase)		
			
		// create training network data		
		val splittedData =
			for (surnamesGroup <- parsedSurnames) yield {
				NetworkDataGenerator.splitSurnames(surnamesGroup, 0, 2)				
			}		
		val trainingSurnames = for (splitted <- splittedData) yield splitted._1
		val testSurnames = for (splitted <- splittedData) yield splitted._2		
			
		val networkInputLength = mappingParser.inputConversionMap.size
		val dataGenerator = new NetworkDataGenerator(networkInputLength, inputConverter)
		
		val trainingData = dataGenerator.generateNetworkData(trainingSurnames)
		val testData = dataGenerator.generateNetworkData(testSurnames)
	}
	
	def printMessage(console: PrintStream) {
		val message = 
			"---------------------- Network Trainer ----------------------\n"+
			"usage:                                                     \n"+
			"trainer map=conv-map.xml trainingData=polish,german,russian\n"+
			"-------------------------------------------------------------"		
		console.println(message)
	}
}